
import sys
import os
sys.path.append('../../icafe')
import parameters as param
import cPickle as pickler

class paramReader():
    
    def __init__(self, filename, log=None):
        
        self.log = log
        self.filename = filename
        self.paramObject = param.Parameters()
        
        self.read()
        
    def read(self):
        
        f = open(self.filename,'r')
        
        path = os.path.abspath(self.filename)
        head,tail = os.path.split(path)
        WORKDIR = head+ os.sep
        self.paramObject.add('WORKDIR',WORKDIR)
        
        if self.log:
            self.log.debug('WORKDIR:' + WORKDIR)
            
        t = f.readline()
        while t:
            if t[0] == '#':
                t = f.readline()
                continue
            t = t.split('=')
            t[0] = t[0].strip()
            t[1] = t[1].strip()
            
            if t[0] in ['OUTPUT_FIELDS','POINTS_OF_INTEREST','OUTPUT_QOI']:
                t[1] = t[1].split(';')
                t[1] = [t1i.strip() for t1i in t[1]]
            else:
                try:
                    t[1] = eval(t[1])
                except:
                    pass
            self.paramObject.add(t[0],t[1])
            t = f.readline()
        
        f.close()
        
        self.pickle()
        
        
            
    
    def pickle(self):
#        print self.paramObject
        pickler.dump(self.paramObject, file(param.TEMPFILE,'w'))
        if self.log:
            self.log.debug('Parameter file pickled at ' + param.TEMPFILE)
        
if __name__ == "__main__":
    
    filename = '../test/full-linear-static.param'
    
    pr = paramReader(filename)
    
    print pr.paramObject
    
    if pr.paramObject.RUN_THIRD_SOFTWARE:
        print 'True'